package com.ifreshwing.view.camera;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;

import com.ifreshwing.utils.Util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by bb on 2015/12/21.
 * 图片处理调用类
 */
public class ImageLocalUtil {
    private Activity context;
    private Bitmap bitmap;
    Integer angle = 0;

    public ImageLocalUtil(Activity context) {
        this.context = context;
    }

    /**
     * 显示指定路径的图片
     *
     * @param filePath
     * @param imageView
     */
    public void decodeFile(String filePath, ImageView imageView) {

        if (filePath.equals("")) {
            return;
        }
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 512;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bitmap = BitmapFactory.decodeFile(filePath, o2);
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        int g;
        Bitmap sbmp;

        sbmp = Bitmap.createScaledBitmap(bitmap, w, h, false);

        imageView.setImageBitmap(sbmp);

    }


    /**
     * 图片缓存并压缩图片
     *
     * @param absolutePath
     */
    public void setimage(String absolutePath, String srcPath) {
        if (absolutePath != null) {

            ExifInterface ei = null;
            try {

                ei = new ExifInterface(absolutePath);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);

            switch (orientation) {

                case ExifInterface.ORIENTATION_ROTATE_90:

                    angle = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:

                    angle = 180;
                    break;

                case ExifInterface.ORIENTATION_ROTATE_270:

                    angle = 270;
                    break;

                case 0:

                    angle = 0;
                    break;
            }

            try {

                Bitmap myBitmap = compBitmap(absolutePath);

                Matrix mat = new Matrix();
                mat.postRotate(angle);

                Bitmap captureBmp = Bitmap.createBitmap(myBitmap, 0, 0,
                        myBitmap.getWidth(), myBitmap.getHeight(), mat, true);
                compressBitmap(captureBmp, srcPath);
//                saveImage(srcPath, compBmp);
                myBitmap.recycle();
                captureBmp.recycle();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            // bitmap = null;
        }
    }

    /**
     * 图片缓存不压缩图片
     *
     * @param absolutePath
     */
    public void setimageOnly(String absolutePath, String srcPath) {

        if (absolutePath != null) {

            ExifInterface ei = null;
            try {

                ei = new ExifInterface(absolutePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);

            switch (orientation) {

                case ExifInterface.ORIENTATION_ROTATE_90:

                    angle = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:

                    angle = 180;
                    break;

                case ExifInterface.ORIENTATION_ROTATE_270:

                    angle = 270;
                    break;

                case 0:

                    angle = 0;
                    break;
            }

            try {

                Bitmap myBitmap = compBitmap(absolutePath);

                Matrix mat = new Matrix();
                mat.postRotate(angle);

                Bitmap captureBmp = Bitmap.createBitmap(myBitmap, 0, 0,
                        myBitmap.getWidth(), myBitmap.getHeight(), mat, true);

                saveImage(srcPath, captureBmp);
                myBitmap.recycle();
                captureBmp.recycle();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            // bitmap = null;
        }

    }

    /**
     * 图片比例大小压缩压缩图片
     */
    public Bitmap compBitmap(String srcPath) {

        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return bitmap;
    }

    /**
     * 图片质量大小压缩压缩图片
     * 并缓存到本地
     */
    public void compressBitmap500(Bitmap image, String srcPath) {
        Log.e("lyf", "压缩了一次");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length > 1024 * 1500) {    //循环判断如果压缩后图片是否大于1Mb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
            Log.e("lyf", "进入while");
        }

        try {
            File file = new File(srcPath);
            file.createNewFile();
            FileOutputStream ostream = new FileOutputStream(file);
            ostream.write(baos.toByteArray());
            ostream.flush();
            ostream.close();
            Log.e("lyf", "进入try");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void compressBitmap(Bitmap image, String srcPath) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length > 1024 * 499) {    //循环判断如果压缩后图片是否大于500Kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }

        try {
            File file = new File(srcPath);
            file.createNewFile();
            FileOutputStream ostream = new FileOutputStream(file);
            ostream.write(baos.toByteArray());
            ostream.flush();
            ostream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void saveImage(String srcPath, Bitmap captureBmp) {

        try {
            File file = new File(srcPath);
            file.createNewFile();
            FileOutputStream ostream = new FileOutputStream(file);
            captureBmp.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
            ostream.flush();
            ostream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("NewApi")
    public static String getPath(final Uri uri, Activity activity) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        if (isKitKat && DocumentsContract.isDocumentUri(activity, uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }

                // TODO handle non-primary volumes
            } else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));

                return getDataColumn(activity, contentUri, null, null);
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(activity, contentUri, selection,
                        selectionArgs);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {

            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(activity, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }


    public static String getDataColumn(Context context, Uri uri,
                                       String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri
                .getAuthority());
    }

//
//    public void selectImage(final  String filePaht) {
//
//        final CharSequence[] items = {context.getResources().getString(R.string.camera_take_phot), context.getResources().getString(R.string.camera_gallery),
//                context.getResources().getString(R.string.camera_cancel)};
//
//        AlertDialog.Builder builder = new AlertDialog.Builder(
//                context);
//        builder.setTitle(context.getResources().getString(R.string.camera_string_title));
//        builder.setItems(items, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int item) {
//                if (items[item].equals(context.getResources().getString(R.string.camera_take_phot))) {
//                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                    File file = new File(filePaht);
//                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
//                    // ******** code for crop image
//
//
//                    intent.putExtra("return-data", true);
//                    context.startActivityForResult(intent,REQUEST_CAMERA);
//                } else if (items[item].equals(context.getResources().getString(R.string.camera_gallery))) {
//
//                    Intent gintent = new Intent();
//                    gintent.setType("image/*");
//                    gintent.setAction(Intent.ACTION_GET_CONTENT);
//
//                    File file = new File(filePaht);
//                    gintent.putExtra("return-data", true);
//                    gintent.putExtra(MediaStore.EXTRA_OUTPUT,
//                            Uri.fromFile(file));
//                    context.startActivityForResult(
//                            Intent.createChooser(gintent, "Select File"),
//                            SELECT_FILE);
//                } else if (items[item].equals(context.getResources().getString(R.string.camera_cancel))) {
//
//                    dialog.dismiss();
//                }
//            }
//        });
//        builder.show();
//    }

    /**
     * 图片列表缓存压缩
     */
    public static List<String> setImagesToOutput(List<String> absolutePathlist) {
        // TODO Auto-generated method stub
        List<String> list = new ArrayList<>();
        Integer angles = 0;
        for (int i = 0; i < absolutePathlist.size(); i++) {

            String absolutePath = absolutePathlist.get(i);

            if (absolutePath.equals("default") || absolutePath.contains("http://")) {
                continue;
            }
            Util.getOutputMediaFile().getAbsolutePath();
            String imagepath = absolutePath.substring(absolutePath.lastIndexOf("/"), absolutePath.length());
            imagepath = Util.getOutputMediaFile().getAbsolutePath() + imagepath;
            if (absolutePath != null) {

                ExifInterface ei = null;
                try {

                    ei = new ExifInterface(absolutePath);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);

                switch (orientation) {

                    case ExifInterface.ORIENTATION_ROTATE_90:

                        angles = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:

                        angles = 180;
                        break;

                    case ExifInterface.ORIENTATION_ROTATE_270:

                        angles = 270;
                        break;

                    case 0:

                        angles = 0;
                        break;
                }

                try {

                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 2;
                    options.inPurgeable = true;
                    options.inInputShareable = true;

                    Bitmap myBitmap = BitmapFactory.decodeFile(absolutePath,
                            options);

                    Matrix mat = new Matrix();
                    mat.postRotate(angles);

                    Bitmap captureBmp = Bitmap.createBitmap(myBitmap, 0, 0,
                            myBitmap.getWidth(), myBitmap.getHeight(), mat, true);

                    File file = new File(imagepath);
                    file.createNewFile();
                    FileOutputStream ostream = new FileOutputStream(file);
                    captureBmp.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
                    ostream.close();
                    while (true) {
                        if (file.length() > 300 * 1000) {
                            ostream = new FileOutputStream(file);
                            captureBmp.compress(Bitmap.CompressFormat.JPEG, 60, ostream);
                            ostream.close();
                        } else {
                            break;
                        }
                    }
                    list.add(imagepath);
                    captureBmp.recycle();
                    myBitmap.recycle();
                } catch (Exception e) {
                    e.printStackTrace();
                }


            } else {
                // bitmap = null;
            }


        }

        return list;
    }

    /**
     * 图片列表缓存压缩feedback
     */
    public List<String> setImagesList(List<String> absolutePathlist) {
        // TODO Auto-generated method stub
        List<String> list = new ArrayList<>();
        for (int i = 0; i < absolutePathlist.size(); i++) {

            String absolutePath = absolutePathlist.get(i);
            if (absolutePath.equals("default")) {
                continue;
            }
            Util.getOutputMediaFile().getAbsolutePath();
            String imagepath = absolutePath.substring(absolutePath.lastIndexOf("/"), absolutePath.length());
            imagepath = Util.getOutputMediaFile().getAbsolutePath() + imagepath;
            setimage(absolutePath, imagepath);
            list.add(imagepath);

        }

        return list;
    }


}
